package org.dentalcard.service;

import org.dentalcard.entity.*;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @user: Vladimir Chernishov
 * @date: 19.12.11
 * @time: 22:30
 */
public class PersistenceManager {

    private static SessionFactory factory;

    private static void init() {
        Configuration conf = new Configuration();
        conf.addAnnotatedClass(DecUser.class);
        conf.addAnnotatedClass(Shift.class);
        conf.addAnnotatedClass(WorkDay.class);
        conf.addAnnotatedClass(Visit.class);
        conf.addAnnotatedClass(Patient.class);
        conf.configure();
        factory = conf.buildSessionFactory();
    }

    public static SessionFactory getFactory() {
        if(factory == null || factory.isClosed()){
            init();
        }
        return factory;
    }

    public static Session getSession(){
        return getFactory().openSession();
    }

    public static void close(){
        if(factory != null && !factory.isClosed()){
            System.out.println("Closing JPA SessionFactory.");
            factory.close();
            System.out.println("JPA SessionFactory is closed.");
        } else {
            System.out.println("JPA SessionFactory is closed.");
        }

    }

    public static void saveOrUpdate(Object entity) {
        Session session = PersistenceManager.getSession();
        try {
            Transaction transaction = session.beginTransaction();
            session.saveOrUpdate(entity);
            session.flush();
            transaction.commit();
        } finally {
            session.close();
        }

    }

    public static void delete(Object entity) {
        Session session = PersistenceManager.getSession();
        try {
            Transaction transaction = session.beginTransaction();
            session.refresh(entity);
            session.delete(entity);
            session.flush();
            transaction.commit();
        } finally {
            session.close();
        }

    }
}
